<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="角色名称:">
        <el-input v-model.trim="query.roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="getAllRoles">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' "
                 size="small" type="primary"
                 icon="el-icon-plus"
                 @click="handleAdd()"
                 style="margin-bottom: 20px;">添加</el-button>
      <el-button :disabled=" userRole !== 'SUPER_ADMIN' "
                 size="small" type="danger"
                 icon="el-icon-document-delete"
                 @click="handleMultiDel()"
                 style="margin-bottom: 20px;">删除</el-button>
    </div>

    <!--  列表数据  -->
    <el-table :data="list" border style="width: 100%" ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" label="序号" width="80" type="index"></el-table-column>
      <el-table-column align="center" prop="roleName" label="角色名称" width="160"></el-table-column>
      <el-table-column align="center" prop="roleCode" label="角色代码" width="200"></el-table-column>
      <el-table-column align="center" prop="roleDesc" label="角色描述" width="300"></el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="220">
        <template slot-scope="scope">
          {{ getFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="220">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="操作" >
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="success" size="mini" @click="handleEdit(scope.row.roleId)">编辑</el-button>
          <el-button icon="el-icon-setting" type="info" size="mini" @click="handlePermission(scope.row.roleId)">分配权限</el-button>
          <el-button :disabled=" userRole !== 'SUPER_ADMIN' " icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer :title="title" :visible.sync="drawer" direction="rtl" :before-close="handleClose" :wrapper-closable="false">
      <el-form :model="role" ref="formData" label-width="120px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="角色名称：" prop="userName">
          <el-input v-model="role.roleName" placeholder="请输入角色名称" show-word-limit maxlength="10" clearable/>
        </el-form-item>
        <el-form-item label="角色代码：" prop="roleCode">
          <el-input v-model="role.roleCode" placeholder="请输入角色代码" show-word-limit maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc">
          <el-input v-model="role.roleDesc" placeholder="请输入角色描述" show-word-limit maxlength="100" clearable type="textarea" :rows="2"/>
        </el-form-item>

      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="danger" plain @click="handleClose">取消</el-button>
        <el-button :disabled=" userRole !== 'SUPER_ADMIN' " size="small" type="success" @click="submit()" :loading="loading">提交</el-button>
      </el-row>
    </el-drawer>

    <!-- 分配权限弹框   -->
    <permission  :roleId="permission.roleId" :visiable="permission.visiable" :remoteClose="remoteClose" />

  </div>
</template>
<script>
import { dateFormat } from '@/utils/date';
import { getUserRole } from "@/utils/userToken";
import { uploadFile } from "@/api/file";
import {getRoles, createRole, editRole, deleteRole, getRoleById} from "@/api/auth";
import Permission from "@/views/permission/index.vue";

export default {
  components: {
    Permission
  },
  data() {
    return {
      permission: {
        visiable: false,
        roleId: null
      },
      query: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        roleName: ''
      },
      list: [],
      roleList: [],
      drawer: false,
      title: "添加角色",
      loading: false,
      valid: true,
      roleCode: '',
      role: {},
      checkedRoles: [],
      checkedRoleIds: [],
      userRole: ''
    }
  },

  created() {
    this.getAllRoles();
    this.userRole = getUserRole();
  },

  methods: {
    // 获取所有的角色信息
    getAllRoles() {
      let data = {
        roleName: this.query.roleName
      }
      getRoles(data).then(res => {
        if (res.code === 200) {
          this.list = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 分配权限
    handlePermission(id) {
      this.permission.roleId = id;
      this.permission.visiable = true;
    },

    // 删除
    handleDel(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          roleIds: []
        }
        data.roleIds.push(id)
        deleteRole(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.getAllRoles();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 批量删除
    handleMultiDel() {
      if (this.checkedRoleIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个角色',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          roleIds: []
        }
        data.roleIds = this.checkedRoleIds;
        deleteRole(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.getAllRoles();
          this.checkedRoleIds = [];
        })
      }).catch(() => {
        // 取消删除
        console.log("取消")
        this.checkedRoleIds = []
      });
    },

    // 编辑
    handleEdit(id) {
      this.title = "编辑角色"
      this.drawer = true;

      getRoleById(id).then(res => {
        if (res.code === 200) {
          this.role = res.data
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 新增角色
    handleAdd() {
      this.drawer = true;
    },

    // 获取当前登录用户的角色
    getRole() {
      this.roleCode = getUserRole();
    },

    // 重置
    reload() {
      this.query.roleName = '';
      this.getAllRoles();
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // 关闭弹框
    handleClose(done) {
      this.drawer = false;
      this.title = "添加角色"
      this.loading = false;
      this.role = {}
      this.getAllRoles();
    },

    handleSelectionChange(val) {
      let len = [];
      this.checkedRoleIds = [];
      len = JSON.parse(JSON.stringify(val))
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedRoleIds.push(len[i].roleId)
        }
      } else {
        this.checkedRoleIds = len
      }
    },

    // 上传封面图
    uploadMainImg(file){
      const data = new FormData();
      data.append('file', file.file);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          console.log(response.data)
          this.user.avatar = response.data;
          this.getAllRoles();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },


    // 提交
    submit() {
      this.loading = true;
      this.beforeSubAndEdit();
      if (!this.valid) {
        this.valid = true;
        this.loading = false;
        return;
      }

      if (this.title === '添加角色') {
        // 添加
        createRole(this.role).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '角色添加成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
          }
        })
        this.valid = true;
        this.loading = false;
      } else {
        // 编辑
        this.valid = true;
        this.loading = false;

        editRole(this.role).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '角色编辑成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.valid = true;
            this.loading = false;
          }
        })
      }
    },

    beforeSubAndEdit() {
      if (!this.role.roleName) {
        console.log(this.role.roleName)
        this.$notify.error({
          title: '错误',
          message: '请输入角色名称',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.role.roleCode) {
        this.$notify.error({
          title: '错误',
          message: '请输入角色代码',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.role.roleDesc) {
        this.$notify.error({
          title: '错误',
          message: '请输入角色描述',
          duration: 1500
        });
        this.valid = false
      }

    },

    // 子组件会触发该方法来关闭窗口
    remoteClose() {
      this.permission.visiable = false;
      this.permission.roleId = null;
      this.getAllRoles();
    },


  }
}
</script>



<style>

</style>
